package com.mediatecture.flex.component
{
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Matrix;
	import flash.net.FileReference;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import mx.charts.chartClasses.NumericAxis;
	import mx.controls.Image;
	import mx.graphics.codec.JPEGEncoder;
	
	public class CustomImageDownloader
	{
		
		private var counter:Number = 0;
		private var _directory:File = File.createTempDirectory();
		
		public function CustomImageDownloader()
		{
		}
		
		public function downloadImages(imgUrls:Array):void
		{	
			var current:Number  = 0;
			
			if(this.directory.exists && this.directory.getDirectoryListing().length > 0)
			{
				for each(var file:File in this.directory.getDirectoryListing())
				{
					file.deleteFile();
				}
			}
			
			for each(var imgUrl in imgUrls)  
			{
				current = current +1;
				var urlLoader:CustomUrlLoader = new CustomUrlLoader();
			
				if (current == imgUrls.length)
				{
					current = 0;
					urlLoader.name = "last";
				}
				urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
				
				urlLoader.imageId= imgUrl.id;
				urlLoader.load(new URLRequest(imgUrl.url));
				
				urlLoader.addEventListener("completed123", imageLoaded);	
			}
		}
			
		protected function imageLoaded(event:CustomUrlLoaderCompletedEvent):void
		{
			var file:File = directory.resolvePath(((event as CustomUrlLoaderCompletedEvent).urlLoader as CustomUrlLoader).imageId.toString() + ".jpg");
			var fileStream:FileStream = new FileStream();
			fileStream.open(file,FileMode.WRITE);
			fileStream.writeBytes((event as CustomUrlLoaderCompletedEvent).urlLoader.data);
			fileStream.close();			
			
			if(((event as CustomUrlLoaderCompletedEvent).urlLoader as CustomUrlLoader).name =="last")
			{
				resizeImages();
			}
		}
		
		private function resizeImages():void
		{
			for each(var file:File in directory.getDirectoryListing())
			{
				resize(file);
			}
		}

		public function get directory():File
		{
			return _directory;
		}
		
		public function resize(image:File):void
		{
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleImageComplete);
			loader.name = image.name;
			loader.load(new URLRequest(image.url));
		}
		private function resizeImage(image:BitmapData, width:Number, heigth:Number ):BitmapData
		{
			var smallImage:Image = new Image();
			smallImage.width =200;
			smallImage.height = 200;
			
			var m:Matrix = new Matrix();
			m.scale(smallImage.width/image.width, smallImage.height/image.height);
			
			smallImage.graphics.beginBitmapFill(image,m,false,true);
			smallImage.graphics.drawRect(0,0,smallImage.width,smallImage.height);
			smallImage.graphics.endFill();
			
			var result:BitmapData = new BitmapData(smallImage.width, smallImage.height, true, 0x00000000);
			result.draw(smallImage);
			
			return result;
		}
		
		protected function handleImageComplete(event:Event):void
		{
			
			var loader:LoaderInfo = event.currentTarget as LoaderInfo; 
			
			var originalImgWidth:Number = loader.width;
			var originalImgHeigth:Number = loader.height;
			
			var bitmapImage:BitmapData = new BitmapData(originalImgWidth, originalImgHeigth, true,0x00000000);
			bitmapImage.draw(loader.content,null,null,null,null,true);
			
			var smallerImage:BitmapData = resizeImage(bitmapImage, 200, 200);
			
			var newImageFile:File = directory.resolvePath(loader.loader.name);
			
			var stream:FileStream = new FileStream();
			stream.open(newImageFile, FileMode.WRITE);
			stream.writeBytes(encodeToJpg(smallerImage), 0, encodeToJpg(smallerImage).length);
			stream.close();
		}
		
		private function encodeToJpg(bmd:BitmapData):ByteArray
		{
			var jpg:JPEGEncoder = new JPEGEncoder();
			return jpg.encode(bmd);
		}

	}
}